#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include "s_config.h"

namespace dhd
{
namespace server
{
   
   namespace po = boost::program_options;
   
   namespace
   {
      void throw_err( const std::string & msg, po::options_description & desc )
      {
          std::cerr << "Usage: dhd_server [-p] <port> [-d] <serve directory> [options]" << std::endl;
          std::cerr << desc << std::endl;
          
          throw ConfigurationError( msg );
      }
   }
   
   
   ServerConfig::ServerConfig( int argc, char * argv[] )
   {
       po::options_description desc("DHD FS server options");
      
       desc.add_options()
           ("help",                                                "displays help message")
           ("port,p",     po::value<int>(),                        "TCP port to accept connections on")
           ("serv_dir,d", po::value<std::string>(),                "Directory to serve out")
           ("srp_db",     po::value<std::string>(),                "SRP Authentication Database file")
           ("use_ssl",     "Use SSL Encrypted TCP connections");
       
       po::positional_options_description p;
      
       p.add("port",     1);
       p.add("serv_dir", 1);
       
       po::variables_map vm;
       
       po::store( po::command_line_parser(argc,argv).options(desc).positional(p).run(), vm );
       po::notify(vm);
              
       if (vm.count("help"))
       {
           std::cout << desc << std::endl;
           throw ConfigurationError("Help Requested");
       }
       
       if (!vm.count("port"))     throw_err("Missing required argument: port", desc);
       if (!vm.count("serv_dir")) throw_err("Missing required argument: serv_dir", desc);
       
       serv_port = vm["port"].as<int>();
       serv_dir  = vm["serv_dir"].as<std::string>();
       
       use_ssl   = vm.count("use_ssl") != 0;
       use_srp   = vm.count("srp_db")  != 0;
       
       if (use_srp)
           srp_database_file = vm["srp_db"].as<std::string>();
           
       // ---- Validate ----
       
       if (serv_port <= 0 || serv_port >= 65535)
           throw_err("Invalid port number", desc);
       
       if ( !( boost::filesystem::exists( serv_dir ) && 
               boost::filesystem::is_directory( serv_dir ) ) )
       {
           throw_err( std::string("Invalid directory: ") + serv_dir, desc );
       }
       
       if ( use_srp && !( boost::filesystem::exists( srp_database_file ) &&
                          boost::filesystem::is_regular_file( srp_database_file ) ) )
       {
           throw_err( std::string("Invalid SRP Database file: ") + srp_database_file, desc );
       }      
   }
   
   
}//end namespace server
}//end namespace dhd

